package com.diy.springframework.step.factory;

import cn.hutool.core.util.ClassLoaderUtil;
import com.diy.springframework.step.FactoryBean;
import com.diy.springframework.step.FactoryBeanRegistrySupport;
import com.diy.springframework.step.processor.BeanPostProcessor;
import com.diy.springframework.step.definition.BeanDefinition;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: diy_spring
 * @description:
 * @author: CaoYong
 * @create: 2021-07-21 09:09
 **/
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();
    private ClassLoader classLoader = ClassLoaderUtil.getClassLoader();

    @Override
    public Object getBean(String name) throws Exception{
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) throws Exception {
        return doGetBean(name, args);
    }

    protected <T> T doGetBean(final String name, final Object[] args) throws Exception {

        Object bean = getSingleton(name);
        if (bean != null) {
//            return (T) bean;
            return (T) getObjectFromFactoryBeanInstance(bean, name);
        }
        BeanDefinition beanDefinition = getBeanDefinition(name);

        return (T) createBean(name, beanDefinition, args);
    }

    private Object getObjectFromFactoryBeanInstance(Object beanInstance, String name) throws Exception {
        if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        }
        Object object = getCachedObjectForFactory(name);

        if (object == null) {
            FactoryBean<?> factoryBean = (FactoryBean<?>) beanInstance;
            object = getObjectFromFactoryBean(factoryBean, name);
        }
        return object;
    }


    protected abstract BeanDefinition getBeanDefinition(String beanName) throws Exception;

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws Exception;

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return this.beanPostProcessors;
    }


    public ClassLoader getClassLoader() {
        return classLoader;
    }
}
